package com.yanx.system.base.query;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.yanx.common.command.Executor;
import com.yanx.common.core.command.PageQryCommand;
import com.yanx.system.base.domain.entity.QSysDept;
import com.yanx.system.base.domain.entity.QSysRole;
import com.yanx.system.base.domain.entity.QSysUser;
import com.yanx.system.base.domain.entity.rel.QSysUserRole;
import com.yanx.system.base.model.qo.SysRoleQo;
import com.yanx.system.base.model.vo.SysRoleVo;
import com.yanx.system.web.infra.utils.DataScopeUtil;
import lombok.AllArgsConstructor;

import java.util.List;

/**
 * 菜单权限分页查询
 *
 * @author: gotanks
 * @create: 2023-4-12
 */
@AllArgsConstructor
public class SysRoleListQry extends PageQryCommand<List<SysRoleVo>> {

    private SysRoleQo sysRoleQo;

    @Override
    public List<SysRoleVo> execute(Executor executor) {
        QSysRole sysRole = QSysRole.sysRole;
        QSysUserRole sysUserRole = QSysUserRole.sysUserRole;
        QSysUser sysUser = QSysUser.sysUser;
        QSysDept sysDept = QSysDept.sysDept;

        //查询条件
        BooleanBuilder condition = DataScopeUtil.getDeptScopeCondition();//数据范围权限
        condition.and(sysRole.deleted.eq(false));
        if (sysRoleQo != null) {
            //自定义查询条件
            if (sysRoleQo.getRoleId() != null && sysRoleQo.getRoleId() != 0) {
                condition.and(sysRole.id.eq(sysRoleQo.getRoleId()));
            }
            if (sysRoleQo.getRoleName() != null && !sysRoleQo.getRoleName().equals("")) {
                condition.and(sysRole.roleName.contains(sysRoleQo.getRoleName()));
            }
            if (sysRoleQo.getStatus() != null && !sysRoleQo.getStatus().equals("")) {
                condition.and(sysRole.status.eq(sysRoleQo.getStatus()));
            }
            if (sysRoleQo.getRoleKey() != null && !sysRoleQo.getRoleKey().equals("")) {
                condition.and(sysRole.roleKey.contains(sysRoleQo.getRoleKey()));
            }
            if (sysRoleQo.getBeginTime() != null) {
                condition.and(sysRole.createTime.gt(sysRoleQo.getBeginTime()));
            }
            if (sysRoleQo.getEndTime() != null) {
                condition.and(sysRole.createTime.lt(sysRoleQo.getEndTime()));
            }
        }

        JPAQuery<SysRoleVo> query = queryFactory.select(SysRoleByIdQry.fields())
                .from(sysRole)
                .leftJoin(sysUserRole).on(sysUserRole.roleId.eq(sysRole.id))
                .leftJoin(sysUser).on(sysUser.id.eq(sysUserRole.userId))
                .leftJoin(sysDept).on(sysUser.deptId.eq(sysDept.id))
                .where(condition);

        return this.pageList(query);
    }

}